package com.atguigu.tingshu.order.context;

import com.atguigu.tingshu.order.interceptor.OrderHandlerInterceptor;
import com.atguigu.tingshu.vo.order.OrderInfoVo;
import org.springframework.beans.BeansException;
import org.springframework.context.ApplicationContext;
import org.springframework.context.ApplicationContextAware;
import org.springframework.stereotype.Component;

import java.util.ArrayList;
import java.util.List;
import java.util.Map;

@Component
public class OrderHandlerInterceptorContext implements ApplicationContextAware {

    // 定义一个List集合管理所有的任务接口的子类对象
    private static List<OrderHandlerInterceptor> orderHandlerInterceptors = new ArrayList<>() ;

    /**
     * @description: 执行责任链中任务的入口方法
     * @author Petrichor
    **/
    public static OrderInfoVo entry(OrderInfoVo orderInfoVo) {
        for(OrderHandlerInterceptor orderHandlerInterceptor : orderHandlerInterceptors) {
            orderInfoVo = orderHandlerInterceptor.sbumitOrderRequestProcess(orderInfoVo);
        }
        return orderInfoVo ;
    }

    @Override
    public void setApplicationContext(ApplicationContext applicationContext) throws BeansException {
        Map<String, OrderHandlerInterceptor> beansOfType = applicationContext.getBeansOfType(OrderHandlerInterceptor.class);
        beansOfType.values().stream()
                .sorted((o1 , o2) -> o1.sort() - o2.sort())
                .forEach(orderHandlerInterceptor -> orderHandlerInterceptors.add(orderHandlerInterceptor));
    }
}